<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="user-card">
          <div class="user-info">
            <div class="avatar-wrapper">
              <!-- 头像地址 -->
              <el-avatar :src="userStore.userInfo.avatar" :size="100"/>
              <!-- 上传头像 -->
              <el-button type="info" class="avatar-edit-btn" circle :icon="Camera" size="small"
                         @click="triggerFileUpload"/>
              <!-- 上传文件域 -->
              <input ref="fileInput" type="file" style="display: none" accept="image/*" @change="handleFileChange"/>
            </div>
            <div class="user-name">
              <!-- 昵称 -->
              <span class="nickname">{{ userStore.userInfo.nickname }}</span>
            </div>
          </div>

        </el-card>
      </el-col>

      <!-- 右侧信息卡片 -->
      <el-col :span="16">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>账号信息</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户名">
              {{ userStore.userInfo.username }}
            </el-descriptions-item>
            <el-descriptions-item label="上一次登录时间">
              {{ timestampFormat(Number(userStore.userInfo.add_date)) }}
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">
              {{ timestampFormat(Number(userStore.userInfo.last_login_date)) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>安全设置</span>
            </div>
          </template>
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">账户密码</div>
              <div class="security-desc">定期修改密码有助于保护账户安全</div>
            </div>
            <el-button type="primary" @click="isShowPasswordChangeDialog = true">
              修改
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <!-- v-model="dialog.visible" :title="dialog.title" -->
    <el-dialog :width="500" v-model="isShowPasswordChangeDialog" title="修改密码"
               @close="resetElement(passwordChangeFormRef)">
      <!-- 修改密码 -->
      <el-form ref="passwordChangeFormRef" :model="passwordChangeForm" :rules="passwordChangeRules" :label-width="100">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordChangeForm.oldPassword" type="password" show-password/>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordChangeForm.newPassword" type="password" show-password/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordChangeForm.confirmPassword" type="password" show-password/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetElement(passwordChangeFormRef)">取消</el-button>
          <el-button type="primary" @click="submitPasswordChangeForm(passwordChangeFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>

import {Camera} from "@element-plus/icons-vue";
import UserAPI from "@/api/system/user.api";
import {useUserStore} from '@/store'
import {timestampFormat} from '@/utils'
import {FormInstance} from "element-plus";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore()
const fileInput = ref<HTMLInputElement | null>(null);

// 退出登录定时器
let timer

// 是否展示修改密码表单
const isShowPasswordChangeDialog = ref<boolean>(false)

// 修改密码表单实例
const passwordChangeFormRef = ref<FormInstance>()

// 修改密码表单初始数据
const passwordChangeForm = ref(
  {oldPassword: '', newPassword: '', confirmPassword: ''}
)

// 重置修改密码表单
const resetElement = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.resetFields(); // 等待表单重置完成
  isShowPasswordChangeDialog.value = false
}

// 提交修改密码表单
const submitPasswordChangeForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 创建副本避免污染原始数据
        const submitData = {...passwordChangeForm.value}
        await UserAPI.changePassword(submitData)
        ElMessage.success('修改密码成功，即将退出登录');
        isShowPasswordChangeDialog.value = false;
        // 修改后退出登录
        timer = setTimeout(() => {
          userStore.logout().then(() => {
            router.push(`/login?redirect=${route.fullPath}`);
          })
        }, 1500)
      } catch (error) {
        console.error('修改密码失败:', error);
        ElMessage.error('修改密码失败');
      } finally {
        timer = null
      }
    }
  })
}

// 检查新密码验证规则
const checkNewPassword = (rule: any, value: any, callback: any) => {
  const regex = /^(?=.*[A-Za-z])(?=.*\d).+$/
  if (!regex.test(value)) {
    callback(new Error('密码必须包含字母和数字'))
  } else if (value === passwordChangeForm.value.oldPassword) {
    callback(new Error('新密码不能跟旧密码相同'))
  } else {
    callback()
  }
}

// 检查重复密码验证规则
const checkConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== passwordChangeForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 修改密码表单验证规则
const passwordChangeRules = reactive({
    oldPassword: [
      {required: true, message: '请输入原密码', trigger: 'blur'},
      {min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur'}
    ],
    newPassword: [
      {required: true, message: '请输入新密码', trigger: 'blur'},
      {min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur'},
      {
        validator: checkNewPassword, trigger: 'blur'
      }
    ],
    confirmPassword: [
      {required: true, message: '请确认新密码', trigger: 'blur'},
      {
        validator: checkConfirmPassword, trigger: 'blur'
      }
    ],
  }
)


const triggerFileUpload = () => {
  // 自执行单击事件
  fileInput.value?.click();
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;
  if (file) {
    let data = await UserAPI.upload(file)
    await UserAPI.updAvatar(data.path)
    userStore.userInfo.avatar = data.server_url + data.path
  } else {
    console.log('无头像')
  }
}

</script>

<style lang="scss" scoped>
.profile-container {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background: var(--el-fill-color-blank);
}

.user-card {
  .user-info {
    padding: 20px 0;
    text-align: center;

    .avatar-wrapper {
      position: relative;
      display: inline-block;
      margin-bottom: 16px;

      .avatar-edit-btn {
        position: absolute;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        border: none;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(0, 0, 0, 0.7);
        }
      }
    }

    .user-name {
      margin-bottom: 8px;

      .nickname {
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .edit-icon {
        margin-left: 8px;
        color: var(--el-text-color-secondary);
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          color: var(--el-color-primary);
        }
      }
    }

    .user-role {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }

  .user-stats {
    display: flex;
    justify-content: space-around;
    padding: 16px 0;

    .stat-item {
      text-align: center;

      .stat-value {
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .stat-label {
        margin-top: 4px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }
  }
}

.info-card,
.security-card {
  margin-bottom: 20px;

  .card-header {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.security-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;

  .security-info {
    .security-title {
      margin-bottom: 4px;
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }

    .security-desc {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}

.el-descriptions {
  .el-descriptions__label {
    font-weight: 500;
    color: var(--el-text-color-regular);
  }

  .el-descriptions__content {
    color: var(--el-text-color-primary);
  }

  .gender-icon {
    margin-left: 8px;
    font-size: 16px;

    &.male {
      color: #409eff;
    }

    &.female {
      color: #f56c6c;
    }
  }
}

.el-dialog {
  .el-dialog__header {
    padding: 20px;
    margin: 0;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  .el-dialog__body {
    padding: 30px 20px;
  }

  .el-dialog__footer {
    padding: 20px;
    border-top: 1px solid var(--el-border-color-light);
  }
}

// 响应式适配
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .el-col {
    width: 100%;
  }
}
</style>
